package com.bianguo.android.httplibrary;

import android.support.annotation.NonNull;

import com.alibaba.fastjson.JSON;
import com.bianguo.android.httplibrary.listener.CallBackListener;

import java.io.UnsupportedEncodingException;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

public class HttpTask<T> implements Runnable, Delayed {

    private IHttpRequest httpRequest;
    private long delayTime;
    private int retryCount;

    public HttpTask(String url, T data, IHttpRequest httpRequest, CallBackListener listener) {
        this.httpRequest = httpRequest;
        this.httpRequest.setUrl(url);
        String content = JSON.toJSONString(data);
        try {
            this.httpRequest.setData(content.getBytes("utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        this.httpRequest.setListener(listener);
    }

    @Override
    public void run() {
        try {
            httpRequest.execute();
        } catch (Exception e) {
            ThreadPoolManager.getInstance().addDelayTask(this);
        }
    }

    @Override
    public long getDelay(@NonNull TimeUnit timeUnit) {
        return this.delayTime - System.currentTimeMillis();
    }

    @Override
    public int compareTo(@NonNull Delayed delayed) {
        return 0;
    }

    public long getDelayTime() {
        return delayTime;
    }

    public void setDelayTime(long delayTime) {
        this.delayTime = delayTime + System.currentTimeMillis();
    }

    public int getRetryCount() {
        return retryCount;
    }

    public void setRetryCount(int retryCount) {
        this.retryCount = retryCount;
    }
}
